package com.xin.spring.framework.xml.factory;

import com.xin.spring.project.util.TransactionManager;

import java.lang.reflect.Proxy;

/**
 * 反射工厂
 *
 * @author xinyue
 */
public class ProxyFactory {

    TransactionManager transactionManager;

    public TransactionManager getTransactionManager() {
        return transactionManager;
    }

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * 获取JDK动态代理对象
     *
     * @param obj 对象
     * @return 结果
     */
    public Object getJdkProxy(Object obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                (proxy, method, args) -> {
                    Object result = null;
                    try {
                        transactionManager.beginTransaction();
                        result = method.invoke(obj, args);
                        transactionManager.commit();
                    } catch (Exception e) {
                        e.printStackTrace();
                        transactionManager.rollback();
                        throw e;
                    } finally {
                        return result;
                    }

                });
    }


}
